package com.server.entity;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 心跳计数器
 */
public class HeartbeatCounter {


    private volatile static HeartbeatCounter heartbeatCounter;

    /**
     * 最后一分钟的心跳数,无锁化,性能更好
     */
    private AtomicLong latestMinuteHeartBeatRate = new AtomicLong(0);

    /**
     * 最后一分钟的时间戳
     */
    private Long latestMinueTimestamp = System.currentTimeMillis();

    /**
     * 获取单例实例
     * @return
     */
    public static HeartbeatCounter getInstance() {
        if (heartbeatCounter == null) {
            synchronized (HeartbeatCounter.class) {
                if (heartbeatCounter == null) {
                    heartbeatCounter = new HeartbeatCounter();
                    return heartbeatCounter;
                }
            }
        }
        return heartbeatCounter;
    }

    /**
     * 心跳计数器增加
     */
    public  void increment() {
        Long currentTime = System.currentTimeMillis();

        if (currentTime - this.latestMinueTimestamp > 60 * 1000L) {
            this.latestMinuteHeartBeatRate = new AtomicLong(0);
            this.latestMinueTimestamp = System.currentTimeMillis();
        }
        //累计加 1
        latestMinuteHeartBeatRate.incrementAndGet();
    }

    /**
     * 获取最近一分钟的心跳次数
     * @return
     */
    public AtomicLong get() {

        return latestMinuteHeartBeatRate;
    }

}
